using System;
using System.Collections.Generic;
using System.Text;
using QuadAnimation.Primitives.Shapes;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using QuadAnimation.Primitives;

namespace QuadAnimation.Animation
{
    public class AnimatedObject
    {
        #region Member Variables
        Quad texturedQuad;
        AnimationSettings settings;
        String currentAnimation;
        float currentAnimationTime;
        int currentFrame;
        Boolean flipped;
        #endregion

        #region Events
        public delegate void AnimationEnd();
        public event AnimationEnd OnAnimationEnd;
        #endregion

        public Boolean Flip
        {
            set { flipped = value; }
        }

        public AnimatedObject(Quad quad, AnimationSettings settings)
        {
            this.texturedQuad = quad;
            this.settings = settings;
            this.currentAnimation = "idle";
            currentAnimationTime = 0f;
            flipped = false;
        }

        public void PlaySequence(String animation)
        {
            currentAnimation = animation;
            currentAnimationTime = 0f;
            AnimationFrame frame;
            settings.frames.TryGetValue(currentAnimation, out frame); 
            //currentFrame = settings.frames[currentAnimation].start;
            currentFrame = frame.start;
        }

        public void Update(GameTime gameTime)
        {
            float elapsedTime = (float)gameTime.ElapsedGameTime.TotalSeconds;
            AnimationFrame frame;
            settings.frames.TryGetValue(currentAnimation, out frame);

            currentAnimationTime += elapsedTime;

            //Has enough time passed to move to the next frame in the animation
            if (currentAnimationTime > frame.timePerFrame)
            {
                currentAnimationTime = 0f;
                currentFrame++;

                //Loop around for now
                if (currentFrame > frame.end)
                {
                    currentFrame = frame.start;

                    //call our event
                    if (OnAnimationEnd != null)
                    {
                        OnAnimationEnd();
                    }
                }
            }
        }

        public void Draw(GraphicsDevice device)
        {
            AnimationHelper.SetCurrentAnimation(texturedQuad, settings, currentFrame, flipped);
            PrimitiveHelper.RenderQuad(device, texturedQuad);
        }
    }
}
